import {
  AddAddress,
  getAddressDetail,
  updateAddress
} from '../../../api/address'
import { toast } from '@/utils/extendApi'
var QQMapWX = require('../../../libs/qqmap-wx-jssdk')
var qqmapsdk
// 1️⃣ 引入 async-validator，async-validator 提供了一个构造函数
import Schema from '../../async-validator/index'
Page({
  // 页面的初始数据
  data: {
    name: '', //收货人
    phone: '', //手机号码
    provinceName: '', //省
    provinceCode: '', //省编码
    cityName: '', //市
    cityCode: '', //市编码
    districtName: '', //区
    districtCode: '', //市编码
    address: '', //详细地址
    fullAddress: '', //完整地址
    isDefault: false //是否设置为默认地址
  },
  // 验证数据

  // 保存收货地址
  async saveAddrssForm(event) {
    const {
      provinceName,
      cityName,
      districtName,
      address,
      isDefault
    } = this.data
    //最终发送的请求参数
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName,
      address,
      isDefault: isDefault ? 1 : 0
    }
    const { valid } = await this.validatorAddress(params)
    if (!valid) return
    const res = this.addressId
      ? await updateAddress(params)
      : await AddAddress(params)
    // console.log(res)
    if (res.code === 200) {
      wx.navigateBack({
        success: () => {
          toast({
            title: this.addressId ? '更新收获地址成功' : '添加收货地址成功'
          })
        }
      })
    }
  },
  validatorAddress(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneRegExp =
      '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneRegExp, message: '收货人手机号不合法' }
      ],
      provinceName: [{ required: true, message: '请选择收货人所在地区' }],
      address: [{ required: true, message: '请输入详细地址' }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  // 省市区选择
  onAddressChange(event) {
    // console.log(event)
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode, cityCode, districtCode] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  // 获取用户地理信息
  // async onLocation() {
  //   // const res = await wx.getLocation()
  //   // console.log(res)
  //   // 获取用户授权信息 判断是否授权地址
  //   const { authSetting } = await wx.getSetting()
  //   // console.log(authSetting)
  //   if (authSetting['scope.userLocation'] === false) {
  //     const modalRes = await modal({
  //       title: '授权提示',
  //       content: '是否允许授权地理位置信息'
  //     })
  //     console.log(modalRes)
  //     if (!modalRes) return toast({ title: '您拒绝了授权' })
  //     const { authSetting } = await wx.openSetting()
  //     if (!authSetting['scope.userLocation']) {
  //       return toast({ title: '您拒绝授权获取地理位置信息' })
  //     }
  //     try {
  //       const res = await wx.getLocation()
  //       // console.log(res)
  //     } catch (error) {
  //       toast({ title: '您拒绝授权获取地理位置信息' })
  //     }
  //   } else {
  //     try {
  //       // const res = await wx.chooseLocation()
  //       // console.log(res)
  //       const res = await wx.getLocation()
  //       // console.log(res)
  //     } catch (error) {
  //       toast({ title: '您拒绝授权获取地理位置信息' })
  //     }
  //   }
  // },
  async onLocation() {
    // 纬度,经度,地名
    const { latitude, longitude, name } = await wx.chooseLocation()
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: (res) => {
        // console.log(res)
        const { adcode, province, city, district } = res.result.ad_info
        const { street, street_number } = res.result.address_component
        const { standard_address } = res.result.formatted_addresses

        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), '0000'),
          districtName: district,
          districtCode: district && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name
        })
      }
    })
  },
  async showAddressInfo(id) {
    if (!id) return
    this.addressId = id //挂载到页面实例上
    wx.setNavigationBarTitle({
      title: '修改收货地址'
    })
    const { data } = await getAddressDetail(id)
    this.setData(data)
  },
  onLoad: function (options) {
    this.showAddressInfo(options.id)
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'XNNBZ-GWEKN-NQVFI-SYWN2-4OHHQ-HWFD7'
    })
  }
})
